<template>
  <div class="app-container">
    <div class="search-container">
      <el-form v-show="showSearch" ref="queryParamsRef" :inline="true" :model="queryParams" label-width="100px">
        <el-form-item label="选择患者" prop="itemName">
          <bed-vs-patient-into-select :bed-blank="'Y'" :clearable="false"
                                      :org-id="userInfo.orgId"
                                      :visit-id="queryParams.visitId" :ward-code="currentSelectDept" class="width-120"
                                      @bed-change="bedChange"/>
        </el-form-item>
        <el-form-item label="查看方式:" prop="isGroupByItemName">
          <el-radio-group v-model="isGroupByItemName" @change="isGroupByItemNameCharge">
            <el-radio value="1">按项目明细查看</el-radio>
            <el-radio value="2">按项目名称汇总查看</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="计费时间段" prop="">
          <el-date-picker v-model="dateRange" :shortcuts="$shortcuts()" :unlink-panels="true"
                          end-placeholder="结束日期" range-separator="截止"
                          start-placeholder="开始日期" type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
                          @change="handleQuery"></el-date-picker>
        </el-form-item>
        <el-form-item label="项目名称" prop="itemName">
          <el-input
            v-model="queryParams.itemName"
            clearable
            placeholder="请输入项目名称"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item v-if="isShowQuery" label="患者姓名" prop="remarks">
          <el-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入患者姓名"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
          <el-button type="primary" @click="printBillDetail">
            <template #icon>
              <i-ep-printer/>
            </template>
            打印
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="10" class="mb8">
      <!--            <el-col :span="1.5">-->
      <!--                <el-button-->
      <!--                    type="primary"-->
      <!--                    plain-->
      <!--                    @click="handleAdd"-->
      <!--                    v-hasPerm="['business:inpBillDetail:add']"-->
      <!--                >-->
      <!--                    <template-->
      <!--                        #icon>-->
      <!--                        <i-ep-plus/>-->
      <!--                    </template>-->
      <!--                    新增-->
      <!--                </el-button>-->
      <!--            </el-col>-->
    </el-row>
    <el-table v-if="isGroupByItemName==='1'" v-adaptive="320" :border="true" :data="inpBillDetailList"
              :header-cell-style="$headerCellStyle" :row-class-name="getRowClass"
              :stripe="true" :summary-method="getSummariesItem" highlight-current-row show-summary>
      <el-table-column :align="'center'" fixed="left" label="费用发生时间" prop="medicalVerifyTime" width="170">
        <template #default="scope">
          <span class="ys-css">{{ $parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip='true' fixed="left" label="医嘱内容"
                       prop="orderText" width="120"/>
      <el-table-column :align="'center'" fixed="left" label="项目类型" prop="itemClass" width="70">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['bill_item_class_dict']" :value="scope.row.itemClass"/>
        </template>
      </el-table-column>
      <el-table-column :align="'left'" :show-overflow-tooltip="true" fixed="left" label="项目名称"
                       prop="itemName"
                       width="160"/>
      <!--            <el-table-column :align="'center'" label="项目编码" prop="itemCode"/>-->
      <el-table-column :align="'left'" header-align="center" label="数量" prop="amount" width="100">
        <template #default="scope">
          <template v-if="!scope.row.isSummary">
                    <span
                      :class="scope.row.amount >= 0 ?'ys-css' : 'ret-ys-css'">{{
                        parseFloat(scope.row.amount.toString()).toFixed(0)
                      }}</span>{{ scope.row.unitsName }}
          </template>
          <template v-else>
            {{ scope.row.amount }}
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'right'" header-align="center" label="单价(元)" prop="itemPrice" width="110">
        <template #default="scope">
          <template v-if="!scope.row.isSummary">
            <span class="ys-css">{{ parseFloat(scope.row.itemPrice.toString()).toFixed(3) }}</span>元
          </template>
          <template v-else>
            {{ scope.row.itemPrice }}
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'right'" header-align="center" label="实收费用(元)" prop="charges" width="110">
        <template #default="scope">
                    <span :class="scope.row.charges >= 0 ?'ys-css' : 'ret-ys-css'">{{
                        scope.row.isSummary ? parseFloat(scope.row.charges.toString()).toFixed(2) : parseFloat(scope.row.charges.toString()).toFixed(3)
                      }}</span>元
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="费用来源" prop="sourceType" width="100"/>
      <el-table-column :align="'center'" label="项目规格" prop="itemSpec" width="120"/>
      <el-table-column :align="'center'" label="开单科室" prop="applyDeptName" width="100"/>
      <el-table-column :align="'center'" label="开单医生" prop="applyDoctorName" width="100"/>
      <el-table-column :align="'center'" label="执行科室" prop="implementDeptName" width="100"/>
      <el-table-column :align="'center'" label="收据分类" prop="classOnInpName"/>
      <el-table-column :align="'center'" label="结算序号" prop="feesNo" width="100"/>
      <el-table-column :align="'center'" label="患者所在科室" prop="deptStayedName" width="100"/>
      <el-table-column :align="'center'" label="患者所在病区" prop="wardCodeName" width="100"/>
      <el-table-column :align="'center'" label="医保是否上传" prop="isUpload" width="100">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['sys_yes_no']" :value="scope.row.isUpload"/>
        </template>
      </el-table-column>
    </el-table>


    <!-- 汇总 -->
    <el-table v-if="isGroupByItemName==='2'" v-adaptive="340" :border="true" :data="groupByItemNameList"
              :header-cell-style="$headerCellStyle"
              :stripe="true" :summary-method="getSummaries" highlight-current-row show-summary>
      <el-table-column :align="'center'" :show-overflow-tooltip='true' fixed="left" label="医嘱内容"
                       prop="orderText" width="120"/>
      <el-table-column :align="'center'" fixed="left" label="项目类型" prop="itemClass" width="150">
        <template #default="scope">
          <dict-data-tag :options="dictDataMap['bill_item_class_dict']" :value="scope.row.itemClass"/>
        </template>
      </el-table-column>
      <el-table-column :align="'center'" :show-overflow-tooltip="true" fixed="left" label="项目名称"
                       prop="itemName"/>
      <el-table-column :align="'center'" label="项目规格" prop="itemSpec" width="170"/>
      <el-table-column :align="'left'" header-align="center" label="数量" prop="amount" width="170">
        <template #default="scope">
          <template v-if="!scope.row.isSummary">
                    <span
                      :class="scope.row.amount >= 0 ?'ys-css' : 'ret-ys-css'">{{
                        parseFloat(scope.row.amount.toString()).toFixed(0)
                      }}</span>{{ scope.row.unitsName }}
          </template>
          <template v-else>
            {{ scope.row.amount }}
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'right'" header-align="center" label="单价(元)" prop="itemPrice" width="170">
        <template #default="scope">
          <template v-if="!scope.row.isSummary">
            <span class="ys-css">{{ parseFloat(scope.row.itemPrice.toString()).toFixed(3) }}</span>元
          </template>
          <template v-else>
            {{ scope.row.itemPrice }}
          </template>
        </template>
      </el-table-column>
      <el-table-column :align="'right'" header-align="center" label="实收费用(元)" prop="charges" width="170">
        <template #default="scope">
                    <span :class="scope.row.charges >= 0 ?'ys-css' : 'ret-ys-css'">{{
                        scope.row.isSummary ? parseFloat(scope.row.charges.toString()).toFixed(2) : parseFloat(scope.row.charges.toString()).toFixed(3)
                      }}</span>元
        </template>
      </el-table-column>
      <el-table-column :align="'center'" label="收据分类" prop="classOnInpName" width="120"/>
      <!--            <el-table-column :align="'center'" label="费用来源" prop="sourceType" width="120"/>-->
    </el-table>
  </div>
</template>
<script lang="ts" setup>
import {useUserStoreHook} from "@/store/modules/user";
import {groupByItemName, listInpBillDetail} from "@/api/hospitalization/inpBillDetail.ts";

import {useDictStoreHook} from "@/store/modules/dict";

const useUserStore = useUserStoreHook();
const dictStore = useDictStoreHook();
let dictDataMap = ref(dictStore.isTypeGetData('spec_unit', 'tally_subject_dict', 'bill_item_class_dict',
  'inp_rcpt_fee_dict', 'sys_yes_no', 'reck_item_class_dict', 'mr_fee_class_dict'))

const {proxy} = getCurrentInstance() as any;
const currentSelectDept = proxy.$currentSelectDept
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const queryParamsRef = ref()
const inpBillDetailList = ref([]);
const groupByItemNameList = ref([]);
const showSearch = ref(true);
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
// 1:按明细查看  2:按项目名称汇总查看
const isGroupByItemName = ref("1")
const props = defineProps({
  isShowQuery: {
    type: Boolean,
    default: true
  }
})
const queryParams = ref({
  patientId: "",
  visitId: "",
  orgId: userInfo.orgId,
  name: "",
  itemName: ''
})

/**
 * 父组件加载初始化方法
 */
function initOpen(obj: any) {
  queryParams.value.visitId = obj.visitId;
  queryParams.value.patientId = obj.patientId;
  isGroupByItemNameCharge()
}

/** 查询住院费用inp_bill_detail列表 */
function getList() {
  if (!queryParams.value.visitId) {
    return ElMessage.error("请选择患者后查询")
  }
  listInpBillDetail(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    inpBillDetailList.value = response.data;
    let dailyTotal = {charges: 0};
    const result: any = [];
    let currentDate = '';
    response.data.forEach((item: any, index: number) => {
      let rowCurrentDate = proxy.$parseTime(item.createTime, '{y}-{m}-{d}')
      // 如果是新的一天，重置合计
      if (rowCurrentDate !== currentDate) {
        // 如果不是第一天，添加前一天的合计行
        if (currentDate) {
          result.push(createSummaryRow(currentDate, dailyTotal));
        }
        currentDate = rowCurrentDate;
        dailyTotal = {charges: 0};
      }
      // 添加当前行
      result.push({...item, isSummary: false});
      // 更新合计，使用 Number 确保类型正确
      dailyTotal.charges += Number(Number(item.charges).toFixed(3));

      // 如果是最后一条记录或者下一条记录是新的一天，添加当前天的合计行
      if (index === response.data.length - 1) {
        result.push(createSummaryRow(currentDate, dailyTotal));
      }
    });
    // 将处理后的结果赋值给表格数据
    inpBillDetailList.value = result;
    return result;
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  isGroupByItemNameCharge();
}

/** 清空 */
function empty() {
  queryParamsRef.value.resetFields()
  dateRange.value = [date + "00:00:00", date + "23:59:59"]
  inpBillDetailList.value = []
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields()
  dateRange.value = [date + "00:00:00", date + "23:59:59"]
  handleQuery();
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('business/inpBillDetail/export', {
    ...queryParams.value
  }, `inpBillDetail_${new Date().getTime()}.xlsx`)
}

function isGroupByItemNameCharge() {
  if (isGroupByItemName.value === '1') {
    getList()
  } else {
    groupByItemNameFun()
  }
}

/**
 * 按项目名称汇总查看
 */
function groupByItemNameFun() {
  groupByItemName(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    groupByItemNameList.value = response.data;
    let dailyTotal = {charges: 0};
    const result: any = [];
    let currentDate = '';
    response.data.forEach((item: any, index: number) => {
      let rowCurrentDate = proxy.$parseTime(item.createTime, '{y}-{m}-{d}')
      // 如果是新的一天，重置合计
      if (rowCurrentDate !== currentDate) {
        // 如果不是第一天，添加前一天的合计行
        if (currentDate) {
          result.push(createSummaryRow(currentDate, dailyTotal));
        }
        currentDate = rowCurrentDate;
        dailyTotal = {charges: 0};
      }
      // 添加当前行
      result.push({...item, isSummary: false});
      // 更新合计，使用 Number 确保类型正确
      dailyTotal.charges += Number(Number(item.charges).toFixed(3));

      // 如果是最后一条记录或者下一条记录是新的一天，添加当前天的合计行
      if (index === response.data.length - 1) {
        result.push(createSummaryRow(currentDate, dailyTotal));
      }
    });
    // 将处理后的结果赋值给表格数据
    groupByItemNameList.value = result;
    return result;
  });
}

// 创建合计行
const createSummaryRow = (date: any, total: any) => ({
  id: `summary-${date}`,
  amount: date.substring(0, 10),
  itemPrice: '当日合计:',
  charges: total.charges + "|",
  isSummary: true
});


// 自定义合计行样式
const getRowClass = ({row}) => {
  return row.isSummary ? 'summary-row' : '';
};

/**
 * 明细合计
 * @param param - 包含 columns 和 data 的对象
 * @returns 包含合计信息的数组
 */
const getSummariesItem = (param: { columns: any[]; data: any[] }) => {
  const {columns, data} = param;
  const sums: (string | VNode)[] = [];

  // 初始化合计值
  let total = 0;

  columns.forEach((column, index) => {
    if (index === 5) {
      // 设置合计标签
      sums[index] = h('div', {style: {float: 'right', color: 'rgb(51, 91, 249)', fontSize: '15px'}}, [
        '合计：',
      ]);
      return;
    }

    if (index === 6) {
      // 提取需要计算的值
      const values = data.map((item) => Number(item[column.property]));
      // 过滤掉 NaN 值并计算总和
      total = values.filter((value) => !Number.isNaN(value)).reduce((prev, curr) => prev + curr, 0);
      // 根据总和是否有效设置结果
      sums[index] = isNaN(total) ? 'N/A' : String(total);
    }
  });

  // 格式化合计金额
  sums[6] = `￥ ${isNaN(total) ? '' : total.toFixed(2)} 元`;
  return sums;
};

const getSummaries = (param: any) => {
  const {columns, data} = param
  const sums: (string | VNode)[] = []
  // 初始化合计值
  let total = 0;

  columns.forEach((column, index) => {
    if (index === 5) {
      // sums[index] = h('div', { style: { textDecoration: 'underline' } }, [
      sums[index] = h('div', {style: {'float': 'right', 'color': 'rgb(51, 91, 249)', 'font-size': '15px'}}, [
        '合计：',
      ])
      return
    }
    if (index === 6) {
      // 提取需要计算的值
      const values = data.map((item) => Number(item[column.property]));
      // 过滤掉 NaN 值并计算总和
      total = values.filter((value) => !Number.isNaN(value)).reduce((prev, curr) => prev + curr, 0);
      // 根据总和是否有效设置结果
      sums[index] = isNaN(total) ? 'N/A' : String(total);
    }
  });

  // 格式化合计金额
  sums[6] = `￥ ${isNaN(total) ? '' : total.toFixed(2)} 元`;
  return sums;
}

/**
 * 切换患者select 点击事件
 * @param obj
 */
function bedChange(obj) {
  queryParams.value.visitId = obj.visitId;
  queryParams.value.patientId = obj.patientId;
  isGroupByItemNameCharge()
}

/**
 * 打印
 */
function printBillDetail() {
  let url = "/business/inpBillDetail/printBillDetail";
  const formData = new FormData()
  if (null != dateRange.value && dateRange.value.length > 0) {
    formData.append("beginTime", dateRange.value[0] ? dateRange.value[0] : "")
    formData.append("endTime", dateRange.value[1] ? dateRange.value[1] : "")
  }
  formData.append("visitId", queryParams.value.visitId)
  formData.append("orgId", queryParams.value.orgId)
  formData.append("operationUser", userInfo.nickName)
  // pdf打印 、打印预览
  proxy.$printPdfPublic(url, formData).then(res => {
    if (res) {
      // objectUrl.value = URL.createObjectURL(res)
      // nextTick(() => {
      // printPreviewRef.value.init(objectUrl.value)
      // })
    } else {
      console.error('打印失败')
    }
  })
}

defineExpose({
  initOpen,
  empty
})
isGroupByItemNameCharge();
</script>

<style>
.summary-row {
  font-weight: bold;
}
</style>
